//
//  FxWebKitView.m
//  MarketManager
//
//  Created by zuqiu on 17/3/13.
//  Copyright © 2017年 finedo. All rights reserved.
//

#import "FxWebKitView.h"

@interface FxWebKitView ()

@end

@implementation FxWebKitView
- (BOOL)prefersStatusBarHidden{
    return NO;
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)pickTimeArr:(NSArray *)arr userDict:(NSDictionary *)dict
{
    if(!arr) {
        return;
    }
    if(!dict) {
        return;
    }
    //Do some right thing

}

- (void)killFunc:(NSString *)funStr
{
    [self.userContentController removeScriptMessageHandlerForName:funStr];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initWKWebView:self.reLastUrl];
   adjustISiPhoneX

//    [self configUI];

    
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [self configUI];
}


#pragma mark - 配置进度条
- (void)configUI {
    UIProgressView *progressView;
    if (ISiPhoneX) {
        // 进度条
     progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 76, self.view.frame.size.width, 5)];
    }else{
     progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 5)];
    }

    // 加载的颜色
    progressView.tintColor = [UIColor orangeColor];
    //为加载的颜色
    progressView.trackTintColor = RgbColor(51, 190, 255);
    [self.view addSubview:progressView];
    [self.view bringSubviewToFront:progressView];
    self.progressView = progressView;
    self.progressView.hidden = YES;
}

#pragma mark - 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.web && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
    
    
//    NSString *contextString = (__bridge NSString *)context;
//    if (!self.web.isLoading && [contextString isEqualToString:@"DJWebKitContext"]) {
//        if([keyPath isEqualToString:@"scrollView.contentSize"])
//        {
//            self.webViewContentHeight = self.web.scrollView.contentSize.height;
//            CGRect frame = self.web.frame;
//            frame.size.height = self.webViewContentHeight;
//            self.web.frame = frame;
//            [self.web sizeToFit];
//        }
//    }
}

#pragma mark - 记得取消监听
- (void)dealloc {
    
    //这里需要注意，前面增加过的方法一定要remove掉。
    [self.web removeObserver:self forKeyPath:@"scrollView.contentSize"];

    [self.web removeObserver:self forKeyPath:@"estimatedProgress"];
    self.web.UIDelegate = nil;
    self.web.navigationDelegate = nil;
    //这里需要注意，前面增加过的方法一定要remove掉。
    [self killFunc:@"pushWeb"];
    [self killFunc:@"callPhone"];
    [self killFunc:@"upPhoto"];
    [self killFunc:@"appExit"];
    [self killFunc:@"mainPage"];
    [self killFunc:@"jwd"];
    [self killFunc:@"postBtn"];
    [self killFunc:@"iosremember"];
    [self killFunc:@"jdandwdforBaidu"];

    

}
- (WKWebViewConfiguration *)webConfig
{ //进行配置控制器
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    //实例化对象
    configuration.userContentController = [WKUserContentController new];
    
//    调用JS方法
       [configuration.userContentController addScriptMessageHandler:self name:@"pushMap"];
       [configuration.userContentController addScriptMessageHandler:self name:@"callPhone"];
       [configuration.userContentController addScriptMessageHandler:self name:@"upPhoto"];
       [configuration.userContentController addScriptMessageHandler:self name:@"appExit"];
       [configuration.userContentController addScriptMessageHandler:self name:@"mainPage"];
       [configuration.userContentController addScriptMessageHandler:self name:@"jwd"];
       [configuration.userContentController addScriptMessageHandler:self name:@"postBtn"];
       [configuration.userContentController addScriptMessageHandler:self name:@"iosremember"];
       [configuration.userContentController addScriptMessageHandler:self name:@"jdandwdforBaidu"];

    //    [configuration.userContentController addScriptMessageHandler:self name:@"iosPay"];upphoto
    //    [configuration.userContentController addScriptMessageHandler:self name:@"commit"];
    //    [configuration.userContentController addScriptMessageHandler:self name:@"iosLogin"];
    //    [configuration.userContentController addScriptMessageHandler:self name:@"appBack"];
    //    [configuration.userContentController addScriptMessageHandler:self name:@"photo"];
    //    [configuration.userContentController addScriptMessageHandler:self name:@"AppExit"];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    configuration.preferences = preferences;
    return configuration;
}




//初始化页面
- (void)initWKWebView:(NSString *)url
{
    
    self.web.backgroundColor = [UIColor yellowColor];
    if (!self.web) {
    self.web = [[WKWebView alloc]initWithFrame:CGRectMake(0, 20, ScreenWidth, ScreenHeight-20)  configuration:[self webConfig]];
    }
//    self.web.scrollView.contentInset =  UIEdgeInsetsMake(-20, 0, 0, 0);
//    [self.web addObserver:self forKeyPath:@"scrollView.contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:@"DJWebKitContext"];

    
    //    NSLog(@"%@",ceshiBaidu);shouYePage
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
    //NSLog(@"viewframe页面加载-->%@",NSStringFromCGRect(self.web.frame));
    [self.web loadRequest:request];
    [self.web sizeToFit];
    // 禁止回弹
    self.web.scrollView.directionalLockEnabled = NO;
    self.web.scrollView.bounces = NO;
    self.web.UIDelegate = self;
    self.web.navigationDelegate = self;
    [self.view addSubview:self.web];
}



#pragma mark - 页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{
    [self.web evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
    
    [self.web evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];

}
- (void)webProsgress
{
    [self.web addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}


- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:prompt preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}



//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
//{
//    NSString *hostname = navigationAction.request.URL.absoluteString;
//
////    if ([navigationAction.request.URL.absoluteString hasPrefix:@"https://itunes.apple.com"])
////    {
////        BA_OpenUrl(navigationAction.request.URL);
////        decisionHandler(WKNavigationActionPolicyCancel);
////    }
////    else
////    {
//        decisionHandler(WKNavigationActionPolicyAllow);
////    }
//}

//- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation
//{
//    NSString *hostname = webView.URL.absoluteString;
//
//
//    [self remind];
//}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{

 
}

#pragma mark - 打电话
-(void)callPhoneMethod:(NSString *)phone
{
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phone];
    //            LPLog(@"str======%@",str);
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
#pragma mark 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
   
}

@end
